#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户认证服务
"""

from datetime import datetime, timedelta
from jose import JWTError, jwt
import hashlib
from sqlalchemy.orm import Session
from app.models.permission_simple import User
from app.core.config import settings

# JWT配置
SECRET_KEY = settings.SECRET_KEY or "your-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24  # 24小时

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码 - 直接比对MD5值（前端已加密）"""
    return plain_password == hashed_password

def get_password_hash(password: str) -> str:
    """获取密码哈希 - 使用MD5"""
    return hashlib.md5(password.encode()).hexdigest()

def create_access_token(data: dict, expires_delta: timedelta = None) -> str:
    """创建访问令牌"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def verify_token(token: str) -> dict:
    """验证令牌"""
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        uid: int = payload.get("uid")
        username: str = payload.get("sub")
        if uid is None or username is None:
            return None
        return {"uid": uid, "username": username}
    except JWTError:
        return None

def authenticate_user(db: Session, username: str, password: str):
    """用户认证"""
    user = db.query(User).filter(User.username == username, User.is_active == True).first()
    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user

def get_user_by_username(db: Session, username: str):
    """根据用户名获取用户"""
    return db.query(User).filter(User.username == username, User.is_active == True).first()

def get_user_by_id(db: Session, user_id: int):
    """根据ID获取用户"""
    return db.query(User).filter(User.id == user_id, User.is_active == True).first()